/**
 * 将链接转成 /redirect?from=[x]&to=[url] 的格式，方便后台按来源统计点击量
 * @author Rox<zhangyi.cn@gmail.com>
 */

(function($) {
    /* main function */
    var apply = function(element, from, tag) {
        if ( $(element).data('applied_stats') ) {
            return element;
        }

        var href = $(element).attr('href');
        if ( !href ) {
            return element;
        }

        var new_href = $.param({
            from: from,
            to:   href,
            tag:  tag
        });
        $(element).attr('href', '/redirect?' + new_href);

        $(element).data('applied_stats', true);
        return element;
    };

    /* jQuery plugin */
    $.fn.apply_stats = function(from, tag) {
        $.each($(this), function(index, item) {
           $(item).bind('mousedown', function(e) {
               apply(item, from, tag);
           });
        });
    };
})(jQuery);
